-- FUNCTION: public.widget_BarChart_Pharmacy_MoreReturningProducts(date, text, integer)

-- DROP FUNCTION public."widget_BarChart_Pharmacy_MoreReturningProducts"(date, text, integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_Pharmacy_MoreReturningProducts"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer)
    RETURNS TABLE("Date" date, "Name" text, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;

begin
create  Temp TABLE temp_table 
( ddate date, 
  dname text,
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";

raise notice 'filtervalue %', filtervalue;

--fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;

for f in SELECT generate_series("fromDate"-filtervalue, "fromDate"+filtervalue,  intervaldata) weeks
    loop 
	raise notice 'fromdate %', "fromDate"-filtervalue;
	raise notice 'todate %', "fromDate"+filtervalue;
	insert into temp_table (ddate,dname,countdata)
------------------------
with returnData as(
select srd."PharmacyProductId",PP."ProductName", count(srd."PharmacyProductId") "Count" 
from "SaleReturnDetail" srd
	
	join "PharmacyProduct" pp on pp."PharmacyProductId" = srd."PharmacyProductId"
	join "SaleReturnHeader" srh on srh."SaleReturnHeaderId" = srd."SaleReturnHeaderId"
	where   srh."CreatedDate"::date >= f.weeks::text::date and srh."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date  
	group by srd."PharmacyProductId" ,PP."ProductName"
	order by "Count" desc 
	limit 10
)

	select f.weeks, rd."ProductName", rd."Count"
from returnData rd;

------------------------  
end loop;
	RETURN QUERY
	
	select A.ddate,A.dname,A.countdata from temp_table A
	order by A.countData desc
	limit "displayCount";
	drop table temp_table;
	--drop table temp_date_table;				
	
END;
$BODY$;

ALTER FUNCTION public."widget_BarChart_Pharmacy_MoreReturningProducts"(date, text, integer)
    OWNER TO postgres;
